﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Helpers;

namespace ShieldNet.Extensions
{
    public class ForgeryToken
    {
        public static string TokenHeaderValue()
        {
            string cookieToken, formToken;
            AntiForgery.GetTokens(null, out cookieToken, out formToken);
            return cookieToken + ":" + formToken;
        }

        public static bool ValidateRequestHeader(HttpRequestBase request)
        {
            string cookieToken = "";
            string formToken = "";
            IEnumerable<string> tokenHeaders = request.Headers.GetValues("RequestVerificationToken");
            string[] tokens = tokenHeaders.First().Split(':');
            if (tokens.Length == 2)
            {
                cookieToken = tokens[0].Trim();
                formToken = tokens[1].Trim();
            }
            try
            {
                AntiForgery.Validate(cookieToken, formToken);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}